﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BUS;
using DTO;

namespace NGU.WUC
{
    public partial class login_box : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {           
        }

        protected void loginBut_Click(object sender, EventArgs e)
        {
            if (this.username.Value.Trim() == "" || this.password.Value == "")
            {
                Response.Redirect("DangNhap.aspx?action=error&type=invalid_input");
            }
            else
            {
                TaiKhoanBUS bus = new TaiKhoanBUS();
                TaiKhoanDTO tk = bus.layThongTinTaiKhoan(this.username.Value, this.password.Value);
                if (tk == null)
                {
                    Response.Redirect("DangNhap.aspx?action=error&type=wrong_info");
                }
                else
                {
                    if (tk.TrangThai == 0)
                    {
                        Response.Redirect("DangNhap.aspx?action=error&type=pending_account");
                    }
                    else
                        if (tk.TrangThai == -1)
                        {
                            Response.Redirect("DangNhap.aspx?action=error&type=blocked_account");
                        }
                    
                    Session["ID"] = tk.MaTaiKhoan;
                    Session["Username"] = tk.Username;
                    Session["TrangThai"] = tk.TrangThai;
                    Session.Timeout = 30;


                    if (this.remember.Checked)
                    {
                        HttpCookie cookie = new HttpCookie("remember", "yes");
                        cookie.Expires = DateTime.Now.AddDays(10);
                        Response.Cookies.Add(cookie);
                        cookie = new HttpCookie("unpw");
                        cookie.Expires = DateTime.Now.AddDays(10);
                        cookie.Values.Add("un", tk.Username);
                        cookie.Values.Add("wp", bus.getMD5(tk.Username + tk.Password));
                        Response.Cookies.Add(cookie);
                    }
                    Response.Redirect(Request.RawUrl);
                }
            }   
        }
        
    }
}